package com.c3w.synchro.member.validator;

import com.c3w.synchro.common.validation.ValidationResult;
import com.c3w.synchro.common.validation.Validator;
import com.c3w.synchro.common.validation.event.ValidationFailedException;
import com.c3w.synchro.member.bean.ContactInfo;
import com.c3w.synchro.member.bean.Member;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.routines.EmailValidator;

/**
 * User: magirard
 * Date: 13-02-09
 */
public class MemberValidator<T extends Member> implements Validator<T> {
    @Override
    public void validate(T bean) throws ValidationFailedException {
        ValidationResult result = new ValidationResult();

        if (bean != null) {
            // 1- Validation de l'athlete
            String name = bean.getName();
            if (name == null) {
                result.add("name", "Name be provided");
            } else if (!GenericValidator.minLength(name, 6)) {
                result.add("name", "name must have a least 6 character");
            }

            // 2 - Validation de l'age
            Integer age = bean.getAge();
            if (age != null) {
                if (!GenericValidator.minValue(age, 0)) {
                    result.add("age", "Age must be over 0");
                } else if (!GenericValidator.maxValue(age, 99)) {
                    result.add("age", "Age must be under 99");
                }
            }

            // 3 - Validation du email
            ContactInfo contactInfo = bean.getContactInfo();
            if (contactInfo != null) {
                String email = contactInfo.getEmail();
                if (email != null) {
                    EmailValidator emailValidator = EmailValidator.getInstance();
                    if (!emailValidator.isValid(email)) {
                        result.add("email", "Le email est invalide");
                    }
                }

                // TODO Valider le reste du contact info.
            }


        } else {
            result.add("Bean", "Bean n'existe pas");
        }

        if (result.getErrorCount() > 0) {
            throw new ValidationFailedException(result);
        }
    }
}
